package com.huang.wangpan.controller;

import com.huang.wangpan.dto.AccessTokenDTO;
import com.huang.wangpan.dto.GithubUser;
import com.huang.wangpan.dao.UserDao;
import com.huang.wangpan.vo.User;
import com.huang.wangpan.provider.GithubProvider;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
public class AuthorizeController {
    @Autowired
    private GithubProvider githubProvider;
    @Resource
    UserDao userDao;
    @Value("${github.client.id}")
    private String clientId;
    @Value("${github.client.secret}")
    private String clientSecret;
    @Value("${github.redirect.url}")
    private String redirectUri;
    // 不可猜测的随机字符串。它用于防止跨站点请求伪造攻击。
    private String state = UUID.randomUUID().toString();

    private static final Logger logger = LoggerFactory.getLogger(AuthorizeController.class);

    @RequestMapping(value = "/authLogin", method = RequestMethod.GET)
    public String githubLogin(HttpServletRequest request) {
        logger.info("AuthorizeController-->/authLogin start......hostname={}", request.getLocalAddr());
        return "redirect:https://github.com/login/oauth/authorize?client_id=" + clientId
                + "&redirect_uri=" + redirectUri
                + "&state=" + state;
    }

    @GetMapping("/githubCallback")
    public String callback(@RequestParam(name = "code") String code,
                           @RequestParam(name = "state") String state,
                           HttpServletRequest request,
                           HttpServletResponse response, Model model) {
        logger.info("AuthorizeController-->/githubCallback start......");
        AccessTokenDTO accessTokenDTO = new AccessTokenDTO();
        accessTokenDTO.setCode(code);
        accessTokenDTO.setRedirect_uri(redirectUri);
        accessTokenDTO.setClient_secret(clientSecret);
        accessTokenDTO.setClinet_id(clientId);
        accessTokenDTO.setState(state);

        GithubUser githubUser = githubProvider.getAccessTokenAndGithubUser(accessTokenDTO);

        //对回调github结果校验,不符合要求直接返回首页
        Boolean flag = checkGithubUser(request, model, githubUser);
        if (!flag) {
            return "hello";
        }
        //保存用户到数据库
        String token = savaUser(githubUser);
        Cookie cookie = new Cookie("token", token);
        cookie.setMaxAge(1800);
        response.addCookie(cookie);

        return "redirect:/";

    }

    /**
     * 保存用户信息
     *
     * @param githubUser githubUser
     * @return token 自己生成的token
     */
    @NotNull
    private String savaUser(GithubUser githubUser) {
        String name = githubUser.getLogin();
        User exsit = userDao.selectByName(name);
        String token=null;
        if(exsit==null){ // 不存在就插入
            User user = new User();
           token = UUID.randomUUID().toString();
            user.setToken(token);
            user.setName(name);
            user.setAccountid(githubUser.getId() + "");
            user.setGmtcreate(System.currentTimeMillis() + "");
            user.setGmtmodified(user.getGmtcreate());
            userDao.insert(user);
        }else { // 存在就更新
            userDao.update(exsit.getName());
            token=exsit.getToken();
        }
        return token;
    }

    /**
     * 检查请求github回调结果，异常直接调回首页
     *
     * @param request
     * @param model
     * @param githubUser
     * @return Boolean
     */
    private Boolean checkGithubUser(HttpServletRequest request, Model model, GithubUser githubUser) {
        if (githubUser == null || githubUser.getLogin() == null || githubUser.getId() == null) {
            String msg2 = "githubUser.getLogin()或者githubUser.getId()不能为空！！";
            logger.error("ERROR:{}", msg2);
            request.getSession().setAttribute("Authorize_fialed_msg3", msg2);
            model.addAttribute("Authorize_fialed_msg2", msg2);
            return false;
        }
        return true;
    }


}
